package com.example.dc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.dc.domain.Weather;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
 * @author curry
 * @version 1.0
 * Create by 2023/10/30 9:30
 */
public class HttpURLConnectionUtils {
    public List<Weather> sendGetRequest(String location){
        String key = "0a01339876ef456b8edc3142452919ef";
        String apiUrl = "https://devapi.qweather.com/v7/weather/24h?location=" + location + "&key=" + key;
        String response = "";
        System.out.println("location"+location);
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(apiUrl);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            /* 3. 设置请求参数（过期时间，输入、输出流、访问方式），以流的形式进行连接 */
            connection.setDoOutput(false);
            // 设置是否从HttpUrlConnection读入
            connection.setDoInput(true);

            connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 设置是否使用缓存
            connection.setUseCaches(true);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            connection.setInstanceFollowRedirects(true);
            // 设置超时时间
            connection.setConnectTimeout(3000);
            // 连接
            connection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = connection.getResponseCode();
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据

            if (code == 200) { // 正常响应
                // 检查响应的 Content-Encoding 是否为 gzip
                String encoding = connection.getContentEncoding();
                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    // 从流中读取响应信息，并解压缩数据
                    GZIPInputStream gzipInputStream = new GZIPInputStream(connection.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response += line + "\n";
                    }
                    reader.close(); // 关闭流
                } else {
                    // 从流中读取响应信息
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response += line + "\n";
                    }
                    reader.close(); // 关闭流
                }
            }
            // 6. 断开连接，释放资源
            connection.disconnect();


        } catch (IOException e) {
            e.printStackTrace();
        }
        //将String字符转为Json对象
        JSONObject jsonObject = JSON.parseObject(response);
        //获取嵌套中的json串,细心观察 content为json数组，里面可放多个json对象
        JSONArray jsonArray = jsonObject.getJSONArray("hourly");
        if(jsonArray==null) return null;
        Gson gson = new Gson();
        Type weatherListType = new TypeToken<List<Weather>>() {}.getType();
        List<Weather> weatherList = gson.fromJson(jsonArray.toString(), weatherListType);
        return weatherList;
    }
}
